﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Diagnostics;
using System.Net;
using System.Net.Cache;
using System.IO;
using System.Diagnostics;

namespace AutoUpdaterDotNET
{
    public partial class UpdateForm : Form
    {
        private System.Timers.Timer _timer;
        public static string _ThuMucGoc
        {
            get
            {
                return System.Windows.Forms.Application.StartupPath;
            }
        }

       
        public UpdateForm(bool remindLater)
        {
            if (!remindLater)
            {
                InitializeComponent();
                var resources = new System.ComponentModel.ComponentResourceManager(typeof(UpdateForm));
                Text = AutoUpdater.DialogTitle;
                labelUpdate.Text = string.Format(resources.GetString("labelUpdate.Text", CultureInfo.CurrentCulture), AutoUpdater.AppTitle);
                labelDescription.Text = string.Format("Phiên bản mới đã được phát hành. Bạn có muốn tải xuống và cập nhật bây giờ?");
            }
        }

        public override sealed string Text
        {
            get { return base.Text; }
            set { base.Text = value; }
        }

        private void UpdateFormLoad(object sender, EventArgs e)
        {
            this.Text = "Cập nhật phần mềm";
            //if (Config.LinkAutoUpdate != null)
            //{
            //    WebRequest webRequest = WebRequest.Create(Config.LinkAutoUpdate + "//LatestVersion.dat");
            //    webRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);

            //    WebResponse webResponse;

            //    try
            //    {
            //        webResponse = webRequest.GetResponse();
            //    }
            //    catch (Exception)
            //    {
            //        return;
            //    }

            //    Stream appCastStream = webResponse.GetResponseStream();
            //    byte[] buffer = new Byte[10000];
            //    int length = appCastStream.Read(buffer, 0, 10000);
            //    string maHoa = System.Text.UTF8Encoding.UTF8.GetString(buffer);
            //}
        }

        private void ButtonUpdateClick(object sender, EventArgs e)
        {
            Process[] runningProcesses = Process.GetProcesses();
            foreach (Process process in runningProcesses)
            {
                if (process.ProcessName.ToUpper().Contains("PAVO"))
                {
                    process.Kill();
                }
            }

            string link = "";
            using (StreamReader sr = File.OpenText(_ThuMucGoc + "\\LatestVersionUpdate.txt"))
            {
                while ((link = sr.ReadLine()) != null)
                {
                    if (link != "")
                    {
                        link += "/LatestUpdate.zip";
                        break;
                    }
                }
            }
            AutoUpdater.DownloadURL = link;
            var downloadDialog = new DownloadUpdateDialog(AutoUpdater.DownloadURL);

            try
            {
                downloadDialog.ShowDialog();
            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                MessageBox.Show(ex.Message);
                this.Close();
            }
        }

        private void ButtonSkipClick(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void ButtonRemindLaterClick(object sender, EventArgs e)
        {
            if(AutoUpdater.LetUserSelectRemindLater)
            {
                var remindLaterForm = new RemindLaterForm();

                var dialogResult = remindLaterForm.ShowDialog();

                if(dialogResult.Equals(DialogResult.OK))
                {
                    AutoUpdater.RemindLaterTimeSpan = remindLaterForm.RemindLaterFormat;
                    AutoUpdater.RemindLaterAt = remindLaterForm.RemindLaterAt;
                }
                else if(dialogResult.Equals(DialogResult.Abort))
                {
                    string link = "";
                    using (StreamReader sr = File.OpenText(_ThuMucGoc + "\\LatestVersionUpdate.txt"))
                    {
                        while ((link = sr.ReadLine()) != null)
                        {
                            if (link != "")
                            {
                                link += "/LatestUpdate.zip";
                                break;
                            }
                        }
                    }
                    AutoUpdater.DownloadURL = link;

                    var downloadDialog = new DownloadUpdateDialog(AutoUpdater.DownloadURL);

                    try
                    {
                        downloadDialog.ShowDialog();
                    }
                    catch (System.Reflection.TargetInvocationException)
                    {
                        return;
                    }
                    return;
                }
                else
                {
                    DialogResult = DialogResult.None;
                    return;
                }
            }
        }

        public void SetTimer(DateTime remindLater)
        {
            TimeSpan timeSpan = remindLater - DateTime.Now;
            _timer = new System.Timers.Timer
                {
                    Interval = (int) timeSpan.TotalMilliseconds
                };
            _timer.Elapsed += TimerElapsed;
            _timer.Start();
        }

        private void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            _timer.Stop();
            AutoUpdater.Start();
        }
    }
}
